<script setup lang="ts">
import {ref, onMounted, reactive} from "vue"
import {CopyToClipboard, formatDate, formatTimestamp} from "@/utils";
import {getWorkOrderDataApi, SpanMethodProps, SummaryMethodProps} from "@/api/customer/dashboard";
import * as echarts from 'echarts';
import {shortcuts} from "@/config/dateDict";
import {ElMessage} from "element-plus";

const calcDesc = `<div  style="font-size: 14px">问题&故障工单分析表的字段说明:
VIP1~VIP4的计算逻辑都一样，以VIP1为例：</br>
- 第二列是工单类型，我们只需要分析问题和故障这两种类型</br>
- <= 30min、30~90min以及>90min表示不同的处理时长</br>
- 不同的时间范围包含2个子列：数量和占比，占比计算公式：当前时间范围内的数量 / 当前行的总数列 * 100</br>
- 总数 = （<= 30min + 30~90min +> 90min）的数量之和</br>
- 总占比 = 当前行工单类型的总数 / 最后一行汇总行（问题或故障）对应的总数列 * 100</br>
</br>
汇总行有两个子行，是对上面不同VIP等级、不同类型的工单数量做一个汇总，</br>
汇总行的总占比： 以问题为例，问题工单总数 / （问题+工单的总数） * 100</br>
</div>
`
const loading = ref(false)
const workOrderNum = ref(null);
const questionNum = ref(null);
const elapsedTime = ref(null);
const workOrderData = reactive({
  count: {
    workType: [],
    total: [],
    done: [],
    todo: []
  },
  vipWorkOrderCount: {
    level: [],
    question: [],
    malfunction: []
  },
  VipWorkOrderTime: "",
  WorkOrderList: "",
  ProblemsFailuresData: "",
})
let workOrderNumChart: echarts.ECharts;
let questionNumChart: echarts.ECharts;
let elapsedTimeChart: echarts.ECharts;

function renderChart() {
  let option
  workOrderData.count.workType = []
  workOrderData.count.total = []
  workOrderData.count.done = []
  workOrderData.count.todo = []
  workOrderData.vipWorkOrderCount.level = []
  workOrderData.vipWorkOrderCount.question = []
  workOrderData.vipWorkOrderCount.malfunction = []
  workOrderNumTable.value = []
  let closedloop
  let i = 0
  let done: number
  let todo: number
  let total: number

  // 处理 工单数量分析 图表所需数据
  for (const key in workOrderData.WorkOrderList) {
    if (Object.hasOwnProperty.call(workOrderData.WorkOrderList, key)) {
      const value = workOrderData.WorkOrderList[key];
      if (value.total !== 0) {
        total = value.total
        done = value.done
        todo = value.todo
        workOrderData.count.workType.push(key)
        workOrderData.count.total.push(total)
        workOrderData.count.done.push(done)
        workOrderData.count.todo.push(todo)

        /** 处理 工单完成情况 表格所需的数据 */
        // 计算闭环率
        closedloop = (done / total * 100).toFixed(1);
        const data = {
          id: i,
          workType: key,
          total,
          done,
          todo,
          closedloop: `${closedloop}%`,
          workOrderList: value.list
        }
        workOrderNumTable.value.push(data)
        i++
      }
    }
  }

  // 处理 VIP工单分布 图表所需数据
  for (let i = 0; i < workOrderData.ProblemsFailuresData.length; i += 2) {
    const question = workOrderData.ProblemsFailuresData[i]
    if (question.level === "汇总") {
      break
    }
    const malfunction = workOrderData.ProblemsFailuresData[i + 1]

    workOrderData.vipWorkOrderCount.level.push(question.level)
    workOrderData.vipWorkOrderCount.question.push(question.total)
    workOrderData.vipWorkOrderCount.malfunction.push(malfunction.total)
  }


  if (workOrderNum.value) {
    option = {
      title: {
        text: '工单数量分析',
        subtext: '不同类型的工单数量',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'none',
          crossStyle: {
            color: '#999'
          }
        }
      },
      legend: {
        data: ['已完成', '未完成'],
        top: 'bottom'
      },
      xAxis: [
        {
          type: 'category',
          data: workOrderData.count.workType,
          axisPointer: {
            type: 'shadow'
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          minInterval: 1,
        }
      ],
      series: [
        {
          name: '已完成',
          type: 'bar',
          data: workOrderData.count.done,
        },
        {
          name: '未完成',
          type: 'bar',
          data: workOrderData.count.todo
        }
      ]
    };
    option && workOrderNumChart.setOption(option);
  }

  if (questionNum.value) {
    option = {
      title: {
        text: 'VIP工单分布',
        subtext: '不同VIP等级的问题/故障工单数量（包含完成和已完成的）',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'none',
          crossStyle: {
            color: '#999'
          }
        }
      },
      legend: {
        data: ['问题', '故障'],
        top: 'bottom'
      },
      xAxis: [
        {
          type: 'category',
          data: workOrderData.vipWorkOrderCount.level,
          axisPointer: {
            type: 'shadow'
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          minInterval: 1,
        }
      ],
      series: [
        {
          name: '问题',
          type: 'bar',
          data: workOrderData.vipWorkOrderCount.question
        },
        {
          name: '故障',
          type: 'bar',
          data: workOrderData.vipWorkOrderCount.malfunction
        }
      ]
    };
    option && questionNumChart.setOption(option);
  }

  if (elapsedTime.value) {
    option = {
      title: {
        text: 'VIP工单耗时',
        subtext: '工单处理时长分析（仅统计已完成的工单）',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'none',
          crossStyle: {
            color: '#999'
          }
        }
      },
      legend: {
        data: ['小于30min', '30~90min之间', '大于90min'],
        top: 'bottom'
      },
      xAxis: [
        {
          type: 'category',
          data: workOrderData.VipWorkOrderTime.level,
          axisPointer: {
            type: 'shadow'
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          minInterval: 1,
        }
      ],
      series: [
        {
          name: '小于30min',
          type: 'bar',
          data: workOrderData.VipWorkOrderTime.lt30
        },
        {
          name: '30~90min之间',
          type: 'bar',
          data: workOrderData.VipWorkOrderTime.gt30Lt90
        },
        {
          name: '大于90min',
          type: 'bar',
          data: workOrderData.VipWorkOrderTime.gt90
        }
      ]
    };
    option && elapsedTimeChart.setOption(option);
  }

}


//#region date select
const endDate = new Date(); // 当前日期
const startDate = new Date(); // 起始日期
startDate.setTime(startDate.getTime() - 3600 * 1000 * 24 * 6)    // 起始日期是6天前

// 设置小时、分钟和秒都为零
startDate.setHours(0, 0, 0, 0);
const timeRange = ref([])
timeRange.value.push(formatDate(startDate))
timeRange.value.push(formatDate(endDate))

//#endregion

async function fetchWorkOrderData() {
  loading.value = true
  let startTimestamp
  let endTimestamp

  if (
    timeRange.value != null &&
    typeof timeRange.value === "object" &&
    Object.keys(timeRange.value).length === 2
  ) {
    let s = timeRange.value[0]
    let e = timeRange.value[1]
    startTimestamp = formatTimestamp(s) - (60 * 60 * 8)
    endTimestamp = formatTimestamp(e) - (60 * 60 * 8)

  }
  try {
    const res = await getWorkOrderDataApi({
      startTime: startTimestamp || undefined,
      endTime: endTimestamp || undefined,
    })
    if (res) {
      workOrderData.VipWorkOrderTime = res.data.list.VipWorkOrderTime
      workOrderData.WorkOrderList = res.data.list.WorkOrderList
      workOrderData.ProblemsFailuresData = res.data.list.ProblemsFailuresData
      renderChart()
      problemsFailuresData.value = workOrderData.ProblemsFailuresData
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

const showWeeklyReport = ref(false)
const workOrderNumTable = ref([]);
const problemsFailuresData = ref([])

const generateWeeklyText = () => {
  showWeeklyReport.value = true

  let total = 0
  let done = 0
  let todo = 0
  let text = ""
  for (let i = 0; i < workOrderNumTable.value.length; i++) {
    const d = workOrderNumTable.value[i]
    let tempText = `${d.workType}: ${d.total},`
    total += d.total
    done += d.done
    todo += d.todo
    text += tempText
  }

  text = `本周售后团队一共处理${total}个工单，完成${done}个工单：(${text})，闭环率${(done / total * 100).toFixed(1)}%`

  CopyToClipboard(text, "周报描述已复制到剪贴板")
}


/** 计算周报表格中的总数 */
const workOrderNumSummaries = (param: SummaryMethodProps) => {
  const {columns, data} = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      return
    }
    if (index === 1) {
      sums[index] = '总数'
      return
    }

    if (index === 5) {
      sums[index] = `${(sums[3] / sums[2] * 100).toFixed(1)}%`
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)}`
    } else {
      sums[index] = 'N/A'
    }
  })

  return sums
}


/** 给工单完成情况的子表格增加背景色 */
const tableRowClassName = ({row}) => {
  if (row.status !== "已完成") {
    return 'danger-row'
  }
  return ''
}

/** 给 问题&故障工单分析 表格增加背景色 */
const problemsFailuresRowClass = ({row}) => {
  if (row.type === "问题") {
    return 'success-row'
  }
  return 'danger-row'
}

const problemsFailuresCellClass = ({column}) => {
  if (column.label === "Level") {
    return 'default_cell'
  }
}


/** 限制表格一次只能展开一行 */
const expandRowKeys = ref([]); // 展开的行的 key 数组
const handleExpandChange = (row, expandedRows) => {
  //表格当前行被展开或收起
  if (expandedRows.length) {
    //说明展开了
    expandRowKeys.value = [];
    if (row) {
      expandRowKeys.value.push(row.id); //只展开当前行id
    }
  } else {
    //说明收起了
    expandRowKeys.value = [];
  }
}


/** el-table 合并行 */
const objectSpanMethod = ({rowIndex, columnIndex,}: SpanMethodProps) => {
  if (columnIndex === 0) {
    if (rowIndex % 2 === 0) {
      return {
        rowspan: 2,
        colspan: 1,
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      }
    }
  }
}

onMounted(async () => {
  workOrderNumChart = echarts.init(workOrderNum.value);
  questionNumChart = echarts.init(questionNum.value);
  elapsedTimeChart = echarts.init(elapsedTime.value);
  await fetchWorkOrderData(); // 获取后端数据
});
</script>

<template>

  <el-dialog
    v-model="showWeeklyReport"
    width="70%"
    align-center
  >
    <template #header>
      <div>
        工作辛苦啦！周报数据已帮您生成了~
        <el-tooltip
          :content=calcDesc
          :raw-content="true"
          placement="right"
        >
          <el-icon color="#46A8F2">
            <QuestionFilled/>
          </el-icon>
        </el-tooltip>

      </div>

    </template>

    <el-tabs type="border-card">
      <el-tab-pane label="工单完成情况">
        <el-table :data="workOrderNumTable" :border="false"
                  style="width: 100%"
                  :summary-method="workOrderNumSummaries"
                  show-summary
                  :row-key="row => row.id"
                  :expand-row-keys='expandRowKeys'
                  @expand-change="handleExpandChange"
        >
          <el-table-column type="expand">
            <template #default="props">
              <el-table :data="props.row.workOrderList"
                        :row-class-name="tableRowClassName"
                        max-height="250px"
                        :border="false">
                <el-table-column label="工单名称" prop="title"/>
                <el-table-column label="客户名称" prop="customer" width="180px"/>
                <el-table-column label="VIP等级" prop="vipLevel" width="150px"/>
                <el-table-column label="负责人" prop="owner" width="150px"/>
                <el-table-column label="状态" prop="status" width="150px"/>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="类型" prop="workType"/>
          <el-table-column label="总数" prop="total"/>
          <el-table-column label="已完成" prop="done"/>
          <el-table-column label="未完成" prop="todo"/>
          <el-table-column label="闭环率" prop="closedloop"/>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="问题&故障工单分析">
        <el-table
          :data="problemsFailuresData"
          :span-method="objectSpanMethod"
          border
          style="width: 100%;"
          :cell-class-name="problemsFailuresCellClass"
          :row-class-name="problemsFailuresRowClass"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
          max-height="500px"
        >
          <el-table-column prop="level" label="Level"/>
          <el-table-column prop="type" label="类型"/>
          <el-table-column label="<= 30min">
            <el-table-column prop="lt30" label="数量"/>
            <el-table-column prop="lt30Proportion" label="占比"/>
          </el-table-column>
          <el-table-column label="30 ~ 90min">
            <el-table-column prop="gt30Lt90" label="数量"/>
            <el-table-column prop="gt30Lt90Proportion" label="占比"/>
          </el-table-column>
          <el-table-column label="> 90min">
            <el-table-column prop="gt90" label="数量"/>
            <el-table-column prop="gt90Proportion" label="占比"/>
          </el-table-column>
          <el-table-column prop="total" label="总数"/>
          <el-table-column prop="totalProportion" label="总占比"/>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>

  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>售后工单数据分析</span>
        <el-button type="primary" link icon="Share"
                   @click="generateWeeklyText()" :loading="loading">生成周报数据
        </el-button>
      </div>
    </template>
    <el-row>
      <el-col :span="22">
        <el-form :inline="true">
          <el-form-item label="选择日期：">
            <el-date-picker
              v-model="timeRange"
              type="daterange"
              unlink-panels
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="shortcuts"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchWorkOrderData()" :loading="loading">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card shadow="hover">
          <div ref="workOrderNum" style="width: 100%; height: 300px;" v-loading="loading"/>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div ref="questionNum" style="width: 100%; height: 300px;" v-loading="loading"/>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div ref="elapsedTime" style="width: 100%; height: 300px;" v-loading="loading"/>
        </el-card>
      </el-col>
    </el-row>
  </el-card>
</template>

<style scoped>
</style>
